﻿namespace Pp.Core.FluentNH
{
    using System.Configuration;
    using System.Data;
    using System.IO;
    using Listeners;
    using Domain.Model;
    using FluentNHibernate.Cfg;
    using FluentNHibernate.Cfg.Db;
    using NHibernate;
    using NHibernate.Event;
    using NHibernate.Tool.hbm2ddl;

    public sealed class ConfigurationItem
    {
        private static readonly ISessionFactory instance;

        static ConfigurationItem()
        { }

        public static ISessionFactory Instance
        {
            get { return instance ?? CreateSessionFactory(); }
        }
        public static NHibernate.Cfg.Configuration NhConfiguration;

        public static ISessionFactory CreateSessionFactory()
        {
            if (instance == null)
            {
                var type = ConfigurationManager.AppSettings.Get("ConnectionType");
                FluentConfiguration b = null;

                switch (type)
                {
                    case "MSSQL":
                        b = Fluently.Configure().Database(MsSqlConfiguration.MsSql2008
                                                              .ConnectionString(d => d.Is(ConfigurationManager.AppSettings.Get("ConnectionString"))))
                            .Mappings(d => d.FluentMappings.AddFromAssemblyOf<EntityBase>());
                        break;
                    case "SqlLite":
                        var persister = SQLiteConfiguration.Standard
                            .UsingFile(ConfigurationManager.AppSettings.Get("ConnectionString"))
                            .ShowSql();
                        b = Fluently.Configure()
                            .Database(persister)
                            .Mappings(d => d.FluentMappings
                                .AddFromAssemblyOf<EntityBase>());
                        break;
                }
                NhConfiguration = b.BuildConfiguration();
                NhConfiguration.SetListener(ListenerType.PreInsert, new CreateUpdateListener());
                NhConfiguration.SetListener(ListenerType.PreUpdate, new CreateUpdateListener());

                return NhConfiguration.BuildSessionFactory();
            }
            return instance;
        }

        public static void DeleteDatabase()
        {
            new SchemaExport(NhConfiguration).Drop(true, true);
        }

        public static void CreateDb()
        {
            if (ConfigurationManager.AppSettings.Get("ConnectionType") == "SqlLite")
                if (File.Exists(ConfigurationManager.AppSettings.Get("ConnectionString")))
                    File.Delete(ConfigurationManager.AppSettings.Get("ConnectionString"));
            new SchemaExport(NhConfiguration).Create(false, true);
        }
    }
}